package com.example.tongyao.utils.encryption;

import java.security.MessageDigest;
import java.util.UUID;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * TongYao2.0 >>> 【com.example.tongyao.utils】
 * MD5加密算法
 *
 * @author: tongyao
 * @since: 2021-08-27 21:03
 */
public class Md5Util {

    /**
     * 加密 生成32位md5码
     * @param inStr
     * @return
     */
    public static String encryption(String inStr){
        MessageDigest md5 = null;
        try{
            md5 = MessageDigest.getInstance("MD5");
        }catch (Exception e){
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++){
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();

    }

    /**
     * 使用shiro中的md5根据盐加密
     * @param password
     * @param salt
     * @return
     */
    public static final String encryptionSalt(String password, String salt){
        //加密方式
        String hashAlgorithmName = "MD5";
        //盐：相同密码使用不同的盐加密后的结果不同
        ByteSource byteSalt = ByteSource.Util.bytes(salt);
        //密码
        Object source = password;
        //加密次数
        int hashIterations = 2;
        SimpleHash result = new SimpleHash(hashAlgorithmName, source, byteSalt, hashIterations);
        return result.toString();
    }

    public static void main(String args[]) {
        System.out.println("原始：" + "123456");
        System.out.println("MD5后：" + encryption("123456"));

        System.out.println(encryptionSalt("abcd", "abcdafasdfasdfasdfasdfasdfasdfad"));
    }


}
